import 'dart:convert';
import 'package:intl/intl.dart';
import 'dart:developer';
import '../../util/_base_export.dart';
import '../../util/_view_export.dart';
import 'package:badges/badges.dart';

import '../../util/app_util.dart';
import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';

class _HomeItem {
  const _HomeItem(
    this.index,
    this.title,
    this.subtitle,
    this.color,
  );

  final int index;
  final String title;
  final String subtitle;
  final Color color;
}

class AccountMsgMainScreen extends StatefulWidget {
  AccountMsgMainScreen({Key? key}) : super(key: key);
  _AccountMsgMainScreenState createState() => _AccountMsgMainScreenState();
}

class _AccountMsgMainScreenState extends State<AccountMsgMainScreen>
    with AfterLayoutMixin<AccountMsgMainScreen>, WidgetsBindingObserver {
  // FirebaseFirestore firestore = FirebaseFirestore.instance;
  @override
  void initState() {
    super.initState();
    slidableController = SlidableController(
        // onSlideAnimationChanged: handleSlideAnimationChanged,
        // onSlideIsOpenChanged: handleSlideIsOpenChanged,
        );
    // listSourceRepository = new OrderHistBloc();
    // listSourceRepository.criteria = {};
  }

  late Animation<double> _rotationAnimation;
  Color _fabColor = Colors.blue;

  void handleSlideAnimationChanged(Animation<double> slideAnimation) {
    setState(() {
      _rotationAnimation = slideAnimation;
    });
  }

  void handleSlideIsOpenChanged(bool isOpen) {
    setState(() {
      _fabColor = isOpen ? Colors.green : Colors.blue;
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      switch (state) {
        case AppLifecycleState.resumed:
          print('resumed');
          // listSourceRepository?.refresh();
          // Handle this case
          break;
        case AppLifecycleState.inactive:
          print('inactive');
          // Handle this case
          break;
        case AppLifecycleState.paused:
          print('paused');
          // Handle this case
          break;
        case AppLifecycleState.detached:
          print('detached');
          // TODO: Handle this case.
          break;
      }
    });
  }

  @override
  void dispose() {
    // listSourceRepository?.dispose();
    super.dispose();
  }

  @override
  void afterFirstLayout(BuildContext context) {
    if ((AppSession.authortoken ?? '').isEmpty)
      App.router.navigateTo(context, AppRoutes.loginSignin);
    else {
      // if ((listSourceRepository.popup_window['title'] ?? '').isNotEmpty)
      //   showDialog(context: context, builder: (_) => _popup_ads(context));
    }
  }

  late SlidableController slidableController;

  // final List<_HomeItem> items = List.generate(
  //   6,
  //   (i) => _HomeItem(
  //     i,
  //     'Tile n°$i',
  //     _getSubtitle(i),
  //     _getAvatarColor(i),
  //   ),
  // );

  CollectionReference lr_app = FirebaseFirestore.instance.collection('app');

  Future<void> updateStatus(String iv_refid) {
    return lr_app
        .doc(AppSession.appUtil.data['uid'].toString())
        .collection('message')
        .doc(iv_refid)
        .update({'status': false})
        .then((value) => setState(() {
              print("User Updated");
            }))
        // .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"));
  }

  Future<void> deleteMsg(String iv_refid) {
    return lr_app
        .doc(AppSession.appUtil.data['uid'].toString())
        .collection('message')
        .doc(iv_refid)
        .delete()
        .then((value) => setState(() {
              print("User Updated");
            }))
        // .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"));
  }

  @override
  Widget build(BuildContext context) {
    print('init');
    return Scaffold(
      // backgroundColor: Colors.transparent,
      appBar: AppBar(
        brightness: Brightness.light,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            child: Icon(
              Icons.chevron_left,
              color: AppColor.blackMain,
              size: 32,
            ),
          ),
        ),
        title: Row(
          children: <Widget>[
            Text(
              '消息',
              style: TextStyle(color: AppColor.blackMain),
            ),
            // Text(
            //   '(amount)',
            //   style: TextStyle(color: AppColor.yellowMain),
            // ),
          ],
        ),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add_alert),
            tooltip: 'Show Snackbar',
            onPressed: () {},
          ),
        ],
      ),
      body: FutureBuilder<QuerySnapshot>(
        future: lr_app
            .doc(AppSession.appUtil.data['uid'].toString())
            .collection('message')
            .orderBy('timestamp', descending: true)
            .limit(20)
            .get(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) {
            return Text("Something went wrong");
          }

          if (snapshot.connectionState == ConnectionState.done) {
            // Map<String, dynamic> data = snapshot.data.data();
            var data = snapshot.data?.docs;
            inspect(data);
            List<Map> _list = [];
            data?.forEach((document) {
              var _link = {};
              _link['data'] = document.data();
              _link['refid'] = document.id;
              _list.add(_link);
              //   _messageBlock(_link, document.id),
              // );
            });
            return OrientationBuilder(
              builder: (context, orientation) => _buildList(context, Axis.vertical, _list),

              // Column(
              // children: _test,
            );
          }

          return Text("loading");
        },
      ),
      // body: Center(
      //   child: OrientationBuilder(
      //     builder: (context, orientation) => _buildList(
      //         context, Axis.vertical  ),
      //         // context, orientation == Orientation.portrait ? Axis.vertical : Axis.horizontal),
      //   ),
      // ),
    );
  }

  Widget _messageBlock(Map iv_message, String iv_refid) {
    print(iv_message['status']);
    var lv_date = DateTime.fromMillisecondsSinceEpoch(iv_message['timestamp'] * 1000);
    var lv_formatted = DateFormat('yyyy-MM-dd hh:mm:ss').format(lv_date); // Apr 8, 2020
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        print('clicked.');
        if (iv_message['status']) await updateStatus(iv_refid);
        AppSession.setMsgPage(
            iv_date: lv_formatted,
            iv_subject: iv_message['subject'],
            iv_content: iv_message['content']);
        App.router.navigateTo(context, AppRoutes.accountMsg);
        // Navigator.pop(context);
      },
      child: Card(
        child: Container(
          height: 120.h,
          padding: EdgeInsets.symmetric(
            horizontal: 25.w,
            vertical: 15.h,
          ),
          child: Column(
            // mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Badge(
                showBadge: (iv_message['status']),
                position: BadgePosition.topStart(top: 0, start: -15),
                badgeContent: null,
                child: Text(
                  lv_formatted,
                  style: AppTextStyle.dateMsg,
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 10.h),
                child: Text(
                  iv_message['subject'] ?? '',
                  style: AppTextStyle.subjectMsg,
                  maxLines: 1,
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Text(
                iv_message['content'] ?? '',
                style: AppTextStyle.contentMsg,
                maxLines: 2,
                softWrap: true,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildList(BuildContext context, Axis direction, List _il_list) {
    return ListView.builder(
      scrollDirection: direction,
      itemBuilder: (context, index) {
        final Axis slidableDirection =
            direction == Axis.horizontal ? Axis.vertical : Axis.horizontal;
        var item = _il_list[index];
        // if (item.index < 8) {
        //   return _getSlidableWithLists(context, index, slidableDirection);
        // } else {
        return _getSlidableWithDelegates(context, index, slidableDirection, item);
        // }
      },
      itemCount: _il_list.length,
    );
  }

  // Widget _getSlidableWithLists(BuildContext context, int index, Axis direction) {
  //   final _HomeItem item = items[index];
  //   //final int t = index;
  //   return Slidable(
  //     key: Key(item.title),
  //     controller: slidableController,
  //     direction: direction,
  //     dismissal: SlidableDismissal(
  //       child: SlidableDrawerDismissal(),
  //       onDismissed: (actionType) {
  //         _showSnackBar(
  //             context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dimiss Delete');
  //         setState(() {
  //           items.removeAt(index);
  //         });
  //       },
  //     ),
  //     actionPane: SlidableDrawerActionPane(), // _getActionPane(item.index),
  //     actionExtentRatio: 0.25,
  //     child: direction == Axis.horizontal
  //         ? VerticalListItem(items[index])
  //         : HorizontalListItem(items[index]),
  //     actions: <Widget>[
  //       IconSlideAction(
  //         caption: 'Archive',
  //         color: Colors.blue,
  //         icon: Icons.archive,
  //         onTap: () => _showSnackBar(context, 'Archive'),
  //       ),
  //       IconSlideAction(
  //         caption: 'Share',
  //         color: Colors.indigo,
  //         icon: Icons.share,
  //         onTap: () => _showSnackBar(context, 'Share'),
  //       ),
  //     ],
  //     secondaryActions: <Widget>[
  //       Container(
  //         height: 800,
  //         color: Colors.green,
  //         child: Text('a'),
  //       ),
  //       IconSlideAction(
  //         caption: 'More',
  //         color: Colors.grey.shade200,
  //         icon: Icons.more_horiz,
  //         onTap: () => _showSnackBar(context, 'More'),
  //         closeOnTap: false,
  //       ),
  //       IconSlideAction(
  //         caption: 'Delete',
  //         color: Colors.red,
  //         icon: Icons.delete,
  //         onTap: () => _showSnackBar(context, 'Delete'),
  //       ),
  //     ],
  //   );
  // }

  Future<bool?> showConfigDialog(){
    return showDialog<bool> (
      context: context,
      builder: (context) {
        return AlertDialog (
          title: Text('确认删除'),
          content: Text('信息将被删除'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () => Navigator.of(context).pop(false),
            ),
            TextButton(
              child: Text('好的'),
              onPressed: () => Navigator.of(context).pop(true),
            )
          ],
        );
      },
    );
  }

  Widget _getSlidableWithDelegates(BuildContext context, int index, Axis direction, Map iw_item) {
    // final _HomeItem item = items[index];

    return Slidable.builder(
      key: Key(iw_item['refid']),
      controller: slidableController,
      direction: direction,
      dismissal: SlidableDismissal(
        child: SlidableDrawerDismissal(),
        closeOnCanceled: true,
        onWillDismiss:(actionType) async {
          bool? s = await showConfigDialog();
          return s??false;
        },
        onDismissed: (actionType) async {
          AppPopup.popupToast('I', '已删除');
          await deleteMsg(iw_item['refid']);
          setState(() {});
        },
      ),
      actionPane: SlidableDrawerActionPane(), //;_getActionPane(item.index)
      actionExtentRatio: 0.25,
      child: _messageBlock(iw_item['data'], iw_item['refid']),
      // direction == Axis.horizontal
      //     ? VerticalListItem(items[index])
      //     : HorizontalListItem(items[index]),

      // actionDelegate: SlideActionBuilderDelegate(
      //     actionCount: 0,
      //     builder: (context, index, animation, renderingMode) {
      //       if (index == 0) {
      //         return IconSlideAction(
      //           caption: 'Archive',
      //           color: renderingMode == SlidableRenderingMode.slide
      //               ? Colors.blue.withOpacity(animation.value)
      //               : (renderingMode == SlidableRenderingMode.dismiss ? Colors.blue : Colors.green),
      //           icon: Icons.archive,
      //           onTap: () async {
      //             var state = Slidable.of(context);
      //             var dismiss = await showDialog<bool>(
      //               context: context,
      //               builder: (context) {
      //                 return AlertDialog(
      //                   title: Text('Delete'),
      //                   content: Text('Item will be deleted'),
      //                   actions: <Widget>[
      //                     FlatButton(
      //                       child: Text('Cancel'),
      //                       onPressed: () => Navigator.of(context).pop(false),
      //                     ),
      //                     FlatButton(
      //                       child: Text('Ok'),
      //                       onPressed: () => Navigator.of(context).pop(true),
      //                     ),
      //                   ],
      //                 );
      //               },
      //             );

      //             if (dismiss) {
      //               state.dismiss();
      //             }
      //           },
      //         );
      //       } else {
      //         return IconSlideAction(
      //           caption: 'Share',
      //           color: renderingMode == SlidableRenderingMode.slide
      //               ? Colors.indigo.withOpacity(animation.value)
      //               : Colors.indigo,
      //           icon: Icons.share,
      //           onTap: () => _showSnackBar(context, 'Share'),
      //         );
      //       }
      //     }),
      secondaryActionDelegate: SlideActionBuilderDelegate(
          actionCount: 1,
          builder: (context, index, animation, renderingMode) {
            // if (index == 0) {
            //   return IconSlideAction(
            //     caption: 'More',
            //     color: renderingMode == SlidableRenderingMode.slide
            //         ? Colors.grey.shade200.withOpacity(animation.value)
            //         : Colors.grey.shade200,
            //     icon: Icons.more_horiz,
            //     onTap: () => _showSnackBar(context, 'More'),
            //     closeOnTap: false,
            //   );
            // } else {
            return IconSlideAction(
              caption: '删除',
              color: renderingMode == SlidableRenderingMode.slide
                  ? Colors.red.withOpacity(animation!.value)
                  : Colors.red,
              icon: Icons.delete,
              onTap: () async {
                AppPopup.popupToast('I', '已删除');
                setState(() async {
                  await deleteMsg(iw_item['refid']);
                });
              },
            );
            // }
          }),
    );
  }

  // static Widget _getActionPane(int index) {
  //   switch (index % 4) {
  //     case 0:
  //       return SlidableBehindActionPane();
  //     case 1:
  //       return SlidableStrechActionPane();
  //     case 2:
  //       return SlidableScrollActionPane();
  //     case 3:
  //       return SlidableDrawerActionPane();
  //     default:
  //       return null;
  //   }
  // }

  // static Color _getAvatarColor(int index) {
  //   switch (index % 4) {
  //     case 0:
  //       return Colors.red;
  //     case 1:
  //       return Colors.green;
  //     case 2:
  //       return Colors.blue;
  //     case 3:
  //       return Colors.indigoAccent;
  //     default:
  //       return null;
  //   }
  // }

  // static String _getSubtitle(int index) {
  //   switch (index % 4) {
  //     case 0:
  //       return 'SlidableBehindActionPane';
  //     case 1:
  //       return 'SlidableStrechActionPane';
  //     case 2:
  //       return 'SlidableScrollActionPane';
  //     case 3:
  //       return 'SlidableDrawerActionPane';
  //     default:
  //       return null;
  //   }
  // }

  void _showSnackBar(BuildContext context, String text) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
  }
}

// class HorizontalListItem extends StatelessWidget {
//   HorizontalListItem(this.item);
//   final _HomeItem item;
//   @override
//   Widget build(BuildContext context) {`
//     return Container(
//       color: Colors.white,
//       width: 160.0,
//       child: Column(
//         mainAxisSize: MainAxisSize.max,
//         children: <Widget>[
//           Expanded(
//             child: CircleAvatar(
//               backgroundColor: item.color,
//               child: Text('${item.index}'),
//               foregroundColor: Colors.white,
//             ),
//           ),
//           Expanded(
//             child: Center(
//               child: Text(
//                 item.subtitle,
//               ),
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }

// class VerticalListItem extends StatelessWidget {
//   VerticalListItem(this.item);
//   final _HomeItem item;

//   @override
//   Widget build(BuildContext context) {
//     return GestureDetector(
//       onTap: () => Slidable.of(context)?.renderingMode == SlidableRenderingMode.none
//           ? Slidable.of(context)?.open()
//           : Slidable.of(context)?.close(),
//       child: Container(
//         color: Colors.white,
//         child: ListTile(
//           leading: CircleAvatar(
//             backgroundColor: item.color,
//             child: Text('${item.index}'),
//             foregroundColor: Colors.white,
//           ),
//           title: Text(item.title),
//           subtitle: Text(item.subtitle),
//         ),
//       ),
//     );
//   }
// }
